﻿using System;
using System.Collections.Generic;
using DimensionsHelper.Common.Contracts.Metadata;

namespace DimensionsHelper.Services.Metadata;

public class Template : MetadataNamedObject, ITemplate
{
    internal Template(IMetadataDocument document, string name, string context)
        : base(document, ObjectType.Template, name)
    {
        Value = string.Empty;
        Context = context;
    }

    internal Template(IMetadataDocument document, string name)
        : this(document, name, document.Context)
    {
    }

    public string Value { get; internal set; }

    public string Context { get; internal set; }

    public bool Equals(ITemplate? other)
    {
        return other != null && 
               Name.Equals(other.Name, StringComparison.OrdinalIgnoreCase) && 
               EqualityComparer<string>.Default.Equals(Value, other.Value);
    }
}


public class Templates : MetadataContextCollection<ITemplate>, ITemplates
{
    internal Templates(IMetadataDocument document, IMetadataObject parent)
        : base(document, ObjectType.Templates, parent)
    {
    }

    internal Templates(IMetadataDocument document) : this(document, document)
    {
    }


    public override ITemplate CreateObject(string name)
    {
        return new Template(Document, name);
    }

    public override ITemplate CreateObject(string name, string context)
    {
        return new Template(Document, name, context);
    }

    public override ITemplate GetByKey(string name)
    {
        var info = GetElementInfoFromKey(name);

        if (!info.IsValid())
        {
            throw new Exception($"关键字'{name}'无效。");
        }

        if (TryGetByKey(name, out var template))
        {
            return template;
        }

        template = new Template(Document, info.Name) { Context = info.Context };
        Add(template);

        return template;
    }

    protected override void OnItemAdded(ITemplate item)
    {
        base.OnItemAdded(item);
        ((Template)item).Parent = this;
    }
}